package router

import (
	"jgt-wallet/src/logger"
	"jgt-wallet/src/util"

	"github.com/facebookgo/inject"
	"github.com/go-session/gear-session"
	"github.com/go-session/mongo"
	"github.com/go-session/session"
	"github.com/spf13/viper"
	"github.com/teambition/gear"
)

// WebRouterV1Handler 初始化web/v1路由
func WebRouterV1Handler(g *inject.Graph) *gear.Router {
	router := gear.NewRouter(gear.RouterOptions{
		Root:                  "/wallet/web/v1",
		IgnoreCase:            true,
		FixedPathRedirect:     true,
		TrailingSlashRedirect: true,
	})

	// session过滤器
	// 注册session中间件(mongo存储)
	msess := viper.GetStringMapString("session")
	router.Use(gearsession.New(
		session.SetCookieName(msess["id"]),
		session.SetSign([]byte(msess["sign"])),
		session.SetStore(
			mongo.NewStore(
				msess["url"],
				msess["db"],
				msess["c"],
			),
		),
	))

	runMode := viper.GetString("run_mode")
	if runMode == util.ProdMode {
		router.Use(func(ctx *gear.Context) error {
			var traceID string
			if v, err := ctx.Any(util.GetTraceIDKey()); err == nil && v != nil {
				traceID = v.(string)
			}

			store := gearsession.FromContext(ctx)
			userID, ok := store.Get(util.SessionUserIDKey)
			if ok {
				ctx.SetAny(util.GetUserIDKey(), userID)
			}
			logger.System(traceID).Infof("访问用户ID:%v，SessionID:%s", userID, store.SessionID())

			if !ok || userID == nil {
				return gear.ErrUnauthorized.WithMsg("用户未登录")
			}

			if v, ok := store.Get(util.SessionUserTypeKey); ok {
				ctx.SetAny(util.GetUserTypeKey(), v)
			}

			return nil
		})
	} else {
		router.Use(DefaultUserMiddleware)
	}

	return router
}
